package com.cardbaobao.cardbabyclient.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.cardbaobao.cardbabyclient.R;
import com.cardbaobao.cardbabyclient.api.Api;
import com.cardbaobao.cardbabyclient.buried.Google;
import com.cardbaobao.cardbabyclient.ui.activity.base.BaseActivity;
import com.cardbaobao.cardbabyclient.ui.adapter.base.CommonAdapter;
import com.cardbaobao.cardbabyclient.ui.adapter.base.ViewHolder;
import com.cardbaobao.cardbabyclient.base.Constant;
import com.cardbaobao.cardbabyclient.callback.ICityInfoCallback;
import com.cardbaobao.cardbabyclient.callback.OnLocationListener;
import com.cardbaobao.cardbabyclient.model.City;
import com.cardbaobao.cardbabyclient.model.CityBase;
import com.cardbaobao.cardbabyclient.model.MyLocation;
import com.cardbaobao.cardbabyclient.utils.AnimationUtil;
import com.cardbaobao.cardbabyclient.utils.ApplicationHelper;
import com.cardbaobao.cardbabyclient.utils.DensityUtil;
import com.cardbaobao.cardbabyclient.buried.GoogleAnalyticsUtil;
import com.cardbaobao.cardbabyclient.utils.JsonUtil;
import com.cardbaobao.cardbabyclient.utils.LocationUtil;
import com.cardbaobao.cardbabyclient.utils.ToastUtil;
import com.cardbaobao.cardbabyclient.utils.UmengEventUtils;
import com.cardbaobao.cardbabyclient.widget.LetterListView;
import com.cardbaobao.cardbabyclient.widget.MyGridView;
import com.cardbaobao.cardbabyclient.widget.TitleBar;
import com.gyf.barlibrary.ImmersionBar;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import rx.Observable;
import rx.Subscriber;

/**
 * 城市选择通用Activity
 * Created by zad
 * 2016/12/22 15:57
 */
public class CitySelectActivity extends BaseActivity implements View.OnClickListener, OnLocationListener, LetterListView.OnTouchingLetterChangedListener {
    /**城市列表请求结果码*/
    public static final int REQUEST_CODE = 0x555;
    /**城市列表请求回调结果KEY*/
    public static final String RESULT_CITY_NAME_KEY = "RESULT_CITY_NAME";
    /**城市列表请求回调城市id*/
    public static final String RESULT_CITY_ID_KEY="RESULT_CITY_ID";

    @BindView(R.id.title_bar)
    TitleBar titleBar;
    @BindView(R.id.id_lv_city_select)
    ListView mLvCity;
    /**
     * 右侧
     */
    @BindView(R.id.id_letter_view)
    LetterListView mLetterListView;
    /**
     * 选中的字母
     */
    @BindView(R.id.id_tv_letter)
    TextView mTvLetter;
    /**
     * 城市名
     */
    private TextView mTvCity;
    /**
     * 定位刷新按钮
     */
    private ImageView mIvRefresh;
    /**
     * 城市列表适配器
     */
    private CommonAdapter<City> mCityListAdapter;
    /**
     * 城市列表数据
     */
    private List<City> mCityList;
    /**
     * 0表示全部(或贷款)城市列表，1表示信用卡申请所使用的城市列表
     */
    private int mTypeCityList = 0;

    private CommonAdapter<CityBase> mCityBaseAdapter;
    /**
     * 保存定位回调信息
     */
    private MyLocation mLocation;

    @Override
    protected void initView(Bundle savedInstanceState) {
        ImmersionBar.with(this).statusBarDarkFont(true,Constant.STATUS_BAR_FONT_ALPHA).init();
        titleBar.setLeftViewOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        initInflater();
        View view_header = mInflater.inflate(R.layout.layout_city_select_header, null);
        view_header.findViewById(R.id.id_ll_city).setOnClickListener(this);//选中定位城市单击事件
        TextView tv_location = (TextView) view_header.findViewById(R.id.id_tv_letter);
        tv_location.setText("定位城市");
        mTvCity = (TextView) view_header.findViewById(R.id.id_tv_city);
        mIvRefresh = (ImageView) view_header.findViewById(R.id.id_iv_refresh);
        /*设置旋转图片等宽高*/
        mIvRefresh.measure(0, 0);
        int img_height = mIvRefresh.getMeasuredHeight();
        int img_width = mIvRefresh.getMeasuredWidth();
        int img_size = Math.max(img_height, img_width);
        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) mIvRefresh.getLayoutParams();
        params.height = img_size;
        params.width = img_size;
        mIvRefresh.setLayoutParams(params);
        /*********************/
        mIvRefresh.setOnClickListener(this);
        mLvCity.addHeaderView(view_header);
        mLvCity.setVisibility(View.GONE);
        mLetterListView.setVisibility(View.GONE);
        mLetterListView.setOnTouchingLetterChangedListener(this);
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        LocationUtil.startLocation(mContext, this);
        mTvCity.setText(" 定位中…");
        mTypeCityList = getIntent().getIntExtra("typeCityList", mTypeCityList);

        //获取城市列表
        showProgressDialog(false, "载入中...");
        Observable<String> observable=mTypeCityList==0?
                Api.getFullCityList():
                Api.getApplyCreditCardCityList();
        observable.subscribe(new Subscriber<String>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                dismissProgressDialog();
                ToastUtil.showToastOnScreenCenter(ApplicationHelper.
                        getApplicationContext().
                        getString(R.string.string_request_server_fail));
                mLetterListView.setVisibility(View.GONE);
                setDataShow(mLvCity, false, "～暂无任何城市～");
            }

            @Override
            public void onNext(String s) {
                dismissProgressDialog();
                List<City> cityList=JsonUtil.getDataLists(s, City.class);
                setCityList(cityList);
            }
        });
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_city_select;
    }

    @Override
    protected void onResume() {
        super.onResume();
        UmengEventUtils.pageEvent(mContext, ApplicationHelper.getApplicationContext().getString(R.string.event_0x005));
        GoogleAnalyticsUtil.setScreenName(Google.CITY_SELECT);
    }

    /**
     * 获取大写字母列表
     *
     * @return
     */
    private List<String> getLetterList() {
        List<String> letterList = new ArrayList<>();
        for (int i = 26; i < 52; i++) {  //大写字母
            int letter = 'A' + i - 26;
            letterList.add(String.valueOf((char) letter));
        }
        return letterList;
    }

    /**
     * 右侧字母列表滑动事件
     *
     * @param text
     * @param isShow
     */
    @Override
    public void onTouchingLetterChanged(String text, boolean isShow) {
        if (isShow) {
            mTvLetter.setVisibility(View.VISIBLE);
            mTvLetter.setText(text);
            mLvCity.setSelection(getPositionForSection(text.charAt(0)));
        } else {
            mTvLetter.setVisibility(View.GONE);
        }
    }

    /**
     * 根据分类的首字母的Char值获取其第一次出现该首字母的位置
     */
    public int getPositionForSection(int section) {
        for (int i = 0, l = mCityList.size(); i < l; i++) {
            if (mCityList.get(i) != null) {
                String letter = mCityList.get(i).getCityFirstLetter();
                char letterChar = letter.toUpperCase().charAt(0);
                if (letterChar == section) {
                    int header_count = mLvCity.getHeaderViewsCount();
                    return i + header_count;
                }
            }
        }
        return -1;
    }

    /**
     * 设置城市列表
     */
    private void setCityList(List<City> cityList) {
        this.mCityList = cityList;
        if (mCityList != null && mCityList.size() > 0) {
            mLvCity.setVisibility(View.VISIBLE);
            mCityListAdapter = new CommonAdapter<City>(mContext, mCityList, R.layout.layout_listview_item_city) {
                @Override
                public void convert(ViewHolder holder, City item, int position) {
                    holder.setText(R.id.id_tv_letter, item.getCityFirstLetter());//字母
                    MyGridView mGvCity = holder.getView(R.id.id_gv_city);//城市GridView
                    if (position == 0) {
                        int padding = DensityUtil.dp2px(mContext, 10);
                        mGvCity.setVerticalSpacing(padding);
                        mGvCity.setHorizontalSpacing(padding);
                    } else {
                        mGvCity.setVerticalSpacing(0);
                        mGvCity.setHorizontalSpacing(0);
                    }
                    if (mGvCity.getTag(R.id.key_city_list) == null) {
                        mCityBaseAdapter = new CommonAdapter<CityBase>(mContext, item.getCityList(), R.layout.item_city_name) {
                            @Override
                            public void convert(ViewHolder holder, CityBase item, int position) {
                                holder.setText(R.id.id_tv_item_city, item.getCityName());
                            }
                        };
                        mGvCity.setAdapter(mCityBaseAdapter);
                        mGvCity.setTag(R.id.key_city_list_adapter, mCityBaseAdapter);
                    } else {
                        mCityBaseAdapter = (CommonAdapter<CityBase>) mGvCity.getTag(R.id.key_city_list_adapter);
                        mCityBaseAdapter.setDataSource(item.getCityList());
                    }
                    if (mGvCity.getTag(R.id.key_city_list) == null) {
                        CityItemClickListener mCityItemClickListener = new CityItemClickListener(item);
                        mGvCity.setTag(R.id.key_city_list, mCityItemClickListener);
                        mGvCity.setOnItemClickListener(mCityItemClickListener);
                    } else {
                        CityItemClickListener mCityItemClickListener = (CityItemClickListener) mGvCity.getTag(R.id.key_city_list);
                        mCityItemClickListener.setData(item);
                    }
                }
            };
            mLvCity.setAdapter(mCityListAdapter);
            mLetterListView.setPinyinList(getLetterList());
            mLetterListView.setVisibility(View.VISIBLE);
        } else {
            mLetterListView.setVisibility(View.GONE);
            setDataShow(mLvCity, false, "～暂无任何城市～");
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.id_iv_refresh:
                //定位刷新
                mTvCity.setTag(null);
                mTvCity.setText(" 定位中…");
                LocationUtil.startLocation(mContext, this);
                /** 开始动画 */
                AnimationUtil.rotateView(mIvRefresh);
                break;
            case R.id.id_ll_city://选择定位城市
                if (mLocation != null) {
                    setCitySelectResult();
                }
                break;
        }
    }

    /**
     * 定位回调
     *
     * @param location   城市位置
     * @param resultCode 定位结果码
     */
    @Override
    public void locationResult(MyLocation location, int resultCode) {
        mLocation = location;
        switch (resultCode) {
            case LocationUtil.LOCATION_FAILURE_CODE:
                mTvCity.setText(" 定位失败，请重试");
                AnimationUtil.stopRotateAnim();
                break;
            case LocationUtil.LOCATION_SUCCESS_CODE:
                final String cityName = location.getCityName();
                LocationUtil.getProvinceCityIDByCityName(new ICityInfoCallback() {
                    @Override
                    public void onCityInfoResponse(City city) {
                        if (city != null) {
                            mTvCity.setTag(city.getID());
                        }
                        AnimationUtil.stopRotateAnim();
                        mTvCity.setText(" " + cityName);
                    }
                }, location.getCityName());
                break;
        }
    }

    private void setCitySelectResult() {
        String cityId= (String) mTvCity.getTag();
        if (TextUtils.isEmpty(cityId)) {
            ToastUtil.showToast("获取城市信息失败，请稍后再试");
        } else {
            Intent intent = getIntent();
            String cityName=mLocation.getCityName();
            //将用户选择的城市名称与城市id保存下来
            LocationUtil.setCityID(cityId);
            LocationUtil.setCityName(cityName);
            intent.putExtra(RESULT_CITY_NAME_KEY, cityName);
            intent.putExtra(RESULT_CITY_ID_KEY, cityId);
            setResult(RESULT_OK, intent);
            finish();
        }
    }

    /**
     * 城市列表单击事件
     */
    private class CityItemClickListener implements AdapterView.OnItemClickListener {
        private City mCity;

        public CityItemClickListener(City mCity) {
            this.mCity = mCity;
        }

        public void setData(City mCity) {
            this.mCity = mCity;
        }

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            String cityName = mCity.getCityList().get(position).getCityName();
            String cityId = mCity.getCityList().get(position).getCityId();
            //将用户选择的城市名称与城市id保存下来
            LocationUtil.setCityID(cityId);
            LocationUtil.setCityName(cityName);
            Intent intent = getIntent();
            intent.putExtra(RESULT_CITY_NAME_KEY, cityName);
            intent.putExtra(RESULT_CITY_ID_KEY, cityId);
            setResult(RESULT_OK, intent);
            finish();
        }
    }

}
